home *** CD-ROM | disk | FTP | other *** search
/ Ultra Pack / UltraComputing Partner Applications.iso / SunLabs / tclTK / src / tcl7.4 / regexp.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-06-22  |  31.2 KB  |  1,311 lines

  1. /*
  2.  * TclRegComp and TclRegExec -- TclRegSub is elsewhere
  3.  *
  4.  *    Copyright (c) 1986 by University of Toronto.
  5.  *    Written by Henry Spencer.  Not derived from licensed software.
  6.  *
  7.  *    Permission is granted to anyone to use this software for any
  8.  *    purpose on any computer system, and to redistribute it freely,
  9.  *    subject to the following restrictions:
  10.  *
  11.  *    1. The author is not responsible for the consequences of use of
  12.  *        this software, no matter how awful, even if they arise
  13.  *        from defects in it.
  14.  *
  15.  *    2. The origin of this software must not be misrepresented, either
  16.  *        by explicit claim or by omission.
  17.  *
  18.  *    3. Altered versions must be plainly marked as such, and must not
  19.  *        be misrepresented as being the original software.
  20.  *
  21.  * Beware that some of this code is subtly aware of the way operator
  22.  * precedence is structured in regular expressions.  Serious changes in
  23.  * regular-expression syntax might require a total rethink.
  24.  *
  25.  * *** NOTE: this code has been altered slightly for use in Tcl: ***
  26.  * *** 1. Use ckalloc and ckfree instead of  malloc and free.     ***
  27.  * *** 2. Add extra argument to regexp to specify the real     ***
  28.  * ***    start of the string separately from the start of the     ***
  29.  * ***    current search. This is needed to search for multiple     ***
  30.  * ***    matches within a string.                 ***
  31.  * *** 3. Names have been changed, e.g. from regcomp to         ***
  32.  * ***    TclRegComp, to avoid clashes with other          ***
  33.  * ***    regexp implementations used by applications.          ***
  34.  * *** 4. Added errMsg declaration and TclRegError procedure     ***
  35.  * *** 5. Various lint-like things, such as casting arguments     ***
  36.  * ***      in procedure calls.                     ***
  37.  *
  38.  * *** NOTE: This code has been altered for use in MT-Sturdy Tcl ***
  39.  * *** 1. All use of static variables has been changed to access ***
  40.  * ***    fields of a structure.                                 ***
  41.  * *** 2. This in addition to changes to TclRegError makes the   ***
  42.  * ***    code multi-thread safe.                                ***
  43.  */
  44.  
  45. static char sccsid[] = "@(#) regexp.c 1.7 95/06/22 08:42:28";
  46.  
  47. #include "tclInt.h"
  48. #include "tclPort.h"
  49.  
  50. /*
  51.  * The variable below is set to NULL before invoking regexp functions
  52.  * and checked after those functions.  If an error occurred then TclRegError
  53.  * will set the variable to point to a (static) error message.  This
  54.  * mechanism unfortunately does not support multi-threading, but the
  55.  * procedures TclRegError and TclGetRegError can be modified to use
  56.  * thread-specific storage for the variable and thereby make the code
  57.  * thread-safe.
  58.  */
  59.  
  60. static char *errMsg = NULL;
  61.  
  62. /*
  63.  * The "internal use only" fields in regexp.h are present to pass info from
  64.  * compile to execute that permits the execute phase to run lots faster on
  65.  * simple cases.  They are:
  66.  *
  67.  * regstart    char that must begin a match; '\0' if none obvious
  68.  * reganch    is the match anchored (at beginning-of-line only)?
  69.  * regmust    string (pointer into program) that match must include, or NULL
  70.  * regmlen    length of regmust string
  71.  *
  72.  * Regstart and reganch permit very fast decisions on suitable starting points
  73.  * for a match, cutting down the work a lot.  Regmust permits fast rejection
  74.  * of lines that cannot possibly match.  The regmust tests are costly enough
  75.  * that TclRegComp() supplies a regmust only if the r.e. contains something
  76.  * potentially expensive (at present, the only such thing detected is * or +
  77.  * at the start of the r.e., which can involve a lot of backup).  Regmlen is
  78.  * supplied because the test in TclRegExec() needs it and TclRegComp() is
  79.  * computing it anyway.
  80.  */
  81.  
  82. /*
  83.  * Structure for regexp "program".  This is essentially a linear encoding
  84.  * of a nondeterministic finite-state machine (aka syntax charts or
  85.  * "railroad normal form" in parsing technology).  Each node is an opcode
  86.  * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
  87.  * all nodes except BRANCH implement concatenation; a "next" pointer with
  88.  * a BRANCH on both ends of it is connecting two alternatives.  (Here we
  89.  * have one of the subtle syntax dependencies:  an individual BRANCH (as
  90.  * opposed to a collection of them) is never concatenated with anything
  91.  * because of operator precedence.)  The operand of some types of node is
  92.  * a literal string; for others, it is a node leading into a sub-FSM.  In
  93.  * particular, the operand of a BRANCH node is the first node of the branch.
  94.  * (NB this is *not* a tree structure:  the tail of the branch connects
  95.  * to the thing following the set of BRANCHes.)  The opcodes are:
  96.  */
  97.  
  98. /* definition    number    opnd?    meaning */
  99. #define    END    0    /* no    End of program. */
  100. #define    BOL    1    /* no    Match "" at beginning of line. */
  101. #define    EOL    2    /* no    Match "" at end of line. */
  102. #define    ANY    3    /* no    Match any one character. */
  103. #define    ANYOF    4    /* str    Match any character in this string. */
  104. #define    ANYBUT    5    /* str    Match any character not in this string. */
  105. #define    BRANCH    6    /* node    Match this alternative, or the next... */
  106. #define    BACK    7    /* no    Match "", "next" ptr points backward. */
  107. #define    EXACTLY    8    /* str    Match this string. */
  108. #define    NOTHING    9    /* no    Match empty string. */
  109. #define    STAR    10    /* node    Match this (simple) thing 0 or more times. */
  110. #define    PLUS    11    /* node    Match this (simple) thing 1 or more times. */
  111. #define    OPEN    20    /* no    Mark this point in input as start of #n. */
  112.             /*    OPEN+1 is number 1, etc. */
  113. #define    CLOSE    30    /* no    Analogous to OPEN. */
  114.  
  115. /*
  116.  * Opcode notes:
  117.  *
  118.  * BRANCH    The set of branches constituting a single choice are hooked
  119.  *        together with their "next" pointers, since precedence prevents
  120.  *        anything being concatenated to any individual branch.  The
  121.  *        "next" pointer of the last BRANCH in a choice points to the
  122.  *        thing following the whole choice.  This is also where the
  123.  *        final "next" pointer of each individual branch points; each
  124.  *        branch starts with the operand node of a BRANCH node.
  125.  *
  126.  * BACK        Normal "next" pointers all implicitly point forward; BACK
  127.  *        exists to make loop structures possible.
  128.  *
  129.  * STAR,PLUS    '?', and complex '*' and '+', are implemented as circular
  130.  *        BRANCH structures using BACK.  Simple cases (one character
  131.  *        per match) are implemented with STAR and PLUS for speed
  132.  *        and to minimize recursive plunges.
  133.  *
  134.  * OPEN,CLOSE    ...are numbered at compile time.
  135.  */
  136.  
  137. /*
  138.  * A node is one char of opcode followed by two chars of "next" pointer.
  139.  * "Next" pointers are stored as two 8-bit pieces, high order first.  The
  140.  * value is a positive offset from the opcode of the node containing it.
  141.  * An operand, if any, simply follows the node.  (Note that much of the
  142.  * code generation knows about this implicit relationship.)
  143.  *
  144.  * Using two bytes for the "next" pointer is vast overkill for most things,
  145.  * but allows patterns to get big without disasters.
  146.  */
  147. #define    OP(p)    (*(p))
  148. #define    NEXT(p)    (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  149. #define    OPERAND(p)    ((p) + 3)
  150.  
  151. /*
  152.  * See regmagic.h for one further detail of program structure.
  153.  */
  154.  
  155.  
  156. /*
  157.  * Utility definitions.
  158.  */
  159. #ifndef CHARBITS
  160. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  161. #else
  162. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  163. #endif
  164.  
  165. #define    FAIL(m)    { TclRegError(m); return(NULL); }
  166. #define    ISMULT(c)    ((c) == '*' || (c) == '+' || (c) == '?')
  167. #define    META    "^$.[()|?+*\\"
  168.  
  169. /*
  170.  * Flags to be passed up and down.
  171.  */
  172. #define    HASWIDTH    01    /* Known never to match null string. */
  173. #define    SIMPLE        02    /* Simple enough to be STAR/PLUS operand. */
  174. #define    SPSTART        04    /* Starts with * or +. */
  175. #define    WORST        0    /* Worst case. */
  176.  
  177. /*
  178.  * Global work variables for TclRegComp().
  179.  */
  180. struct regcomp_state  {
  181.     char *regparse;        /* Input-scan pointer. */
  182.     int regnpar;        /* () count. */
  183.     char *regcode;        /* Code-emit pointer; ®dummy = don't. */
  184.     long regsize;        /* Code size. */
  185. };
  186.  
  187. static char regdummy;
  188.  
  189. /*
  190.  * The first byte of the regexp internal "program" is actually this magic
  191.  * number; the start node begins in the second byte.
  192.  */
  193. #define    MAGIC    0234
  194.  
  195.  
  196. /*
  197.  * Forward declarations for TclRegComp()'s friends.
  198.  */
  199. #ifndef STATIC
  200. #define    STATIC    static
  201. #endif
  202. STATIC char *reg();
  203. STATIC char *regbranch();
  204. STATIC char *regpiece();
  205. STATIC char *regatom();
  206. STATIC char *regnode();
  207. STATIC char *regnext();
  208. STATIC void regc();
  209. STATIC void reginsert();
  210. STATIC void regtail();
  211. STATIC void regoptail();
  212. #ifdef STRCSPN
  213. STATIC int strcspn();
  214. #endif
  215.  
  216. /*
  217.  - TclRegComp - compile a regular expression into internal code
  218.  *
  219.  * We can't allocate space until we know how big the compiled form will be,
  220.  * but we can't compile it (and thus know how big it is) until we've got a
  221.  * place to put the code.  So we cheat:  we compile it twice, once with code
  222.  * generation turned off and size counting turned on, and once "for real".
  223.  * This also means that we don't allocate space until we are sure that the
  224.  * thing really will compile successfully, and we never have to move the
  225.  * code and thus invalidate pointers into it.  (Note that it has to be in
  226.  * one piece because free() must be able to free it all.)
  227.  *
  228.  * Beware that the optimization-preparation code in here knows about some
  229.  * of the structure of the compiled regexp.
  230.  */
  231. regexp *
  232. TclRegComp(exp)
  233. char *exp;
  234. {
  235.     register regexp *r;
  236.     register char *scan;
  237.     register char *longest;
  238.     register int len;
  239.     int flags;
  240.     struct regcomp_state state;
  241.     struct regcomp_state *rcstate= &state;
  242.  
  243.     if (exp == NULL)
  244.         FAIL("NULL argument");
  245.  
  246.     /* First pass: determine size, legality. */
  247.     rcstate->regparse = exp;
  248.     rcstate->regnpar = 1;
  249.     rcstate->regsize = 0L;
  250.     rcstate->regcode = ®dummy;
  251.     regc(MAGIC, rcstate);
  252.     if (reg(0, &flags, rcstate) == NULL)
  253.         return(NULL);
  254.  
  255.     /* Small enough for pointer-storage convention? */
  256.     if (rcstate->regsize >= 32767L)        /* Probably could be 65535L. */
  257.         FAIL("regexp too big");
  258.  
  259.     /* Allocate space. */
  260.     r = (regexp *)ckalloc(sizeof(regexp) + (unsigned)rcstate->regsize);
  261.     if (r == NULL)
  262.         FAIL("out of space");
  263.  
  264.     /* Second pass: emit code. */
  265.     rcstate->regparse = exp;
  266.     rcstate->regnpar = 1;
  267.     rcstate->regcode = r->program;
  268.     regc(MAGIC, rcstate);
  269.     if (reg(0, &flags, rcstate) == NULL)
  270.         return(NULL);
  271.  
  272.     /* Dig out information for optimizations. */
  273.     r->regstart = '\0';    /* Worst-case defaults. */
  274.     r->reganch = 0;
  275.     r->regmust = NULL;
  276.     r->regmlen = 0;
  277.     scan = r->program+1;            /* First BRANCH. */
  278.     if (OP(regnext(scan)) == END) {        /* Only one top-level choice. */
  279.         scan = OPERAND(scan);
  280.  
  281.         /* Starting-point info. */
  282.         if (OP(scan) == EXACTLY)
  283.             r->regstart = *OPERAND(scan);
  284.         else if (OP(scan) == BOL)
  285.             r->reganch++;
  286.  
  287.         /*
  288.          * If there's something expensive in the r.e., find the
  289.          * longest literal string that must appear and make it the
  290.          * regmust.  Resolve ties in favor of later strings, since
  291.          * the regstart check works with the beginning of the r.e.
  292.          * and avoiding duplication strengthens checking.  Not a
  293.          * strong reason, but sufficient in the absence of others.
  294.          */
  295.         if (flags&SPSTART) {
  296.             longest = NULL;
  297.             len = 0;
  298.             for (; scan != NULL; scan = regnext(scan))
  299.                 if (OP(scan) == EXACTLY && ((int) strlen(OPERAND(scan))) >= len) {
  300.                     longest = OPERAND(scan);
  301.                     len = strlen(OPERAND(scan));
  302.                 }
  303.             r->regmust = longest;
  304.             r->regmlen = len;
  305.         }
  306.     }
  307.  
  308.     return(r);
  309. }
  310.  
  311. /*
  312.  - reg - regular expression, i.e. main body or parenthesized thing
  313.  *
  314.  * Caller must absorb opening parenthesis.
  315.  *
  316.  * Combining parenthesis handling with the base level of regular expression
  317.  * is a trifle forced, but the need to tie the tails of the branches to what
  318.  * follows makes it hard to avoid.
  319.  */
  320. static char *
  321. reg(paren, flagp, rcstate)
  322. int paren;            /* Parenthesized? */
  323. int *flagp;
  324. struct regcomp_state *rcstate;
  325. {
  326.     register char *ret;
  327.     register char *br;
  328.     register char *ender;
  329.     register int parno = 0;
  330.     int flags;
  331.  
  332.     *flagp = HASWIDTH;    /* Tentatively. */
  333.  
  334.     /* Make an OPEN node, if parenthesized. */
  335.     if (paren) {
  336.         if (rcstate->regnpar >= NSUBEXP)
  337.             FAIL("too many ()");
  338.         parno = rcstate->regnpar;
  339.         rcstate->regnpar++;
  340.         ret = regnode(OPEN+parno,rcstate);
  341.     } else
  342.         ret = NULL;
  343.  
  344.     /* Pick up the branches, linking them together. */
  345.     br = regbranch(&flags,rcstate);
  346.     if (br == NULL)
  347.         return(NULL);
  348.     if (ret != NULL)
  349.         regtail(ret, br);    /* OPEN -> first. */
  350.     else
  351.         ret = br;
  352.     if (!(flags&HASWIDTH))
  353.         *flagp &= ~HASWIDTH;
  354.     *flagp |= flags&SPSTART;
  355.     while (*rcstate->regparse == '|') {
  356.         rcstate->regparse++;
  357.         br = regbranch(&flags,rcstate);
  358.         if (br == NULL)
  359.             return(NULL);
  360.         regtail(ret, br);    /* BRANCH -> BRANCH. */
  361.         if (!(flags&HASWIDTH))
  362.             *flagp &= ~HASWIDTH;
  363.         *flagp |= flags&SPSTART;
  364.     }
  365.  
  366.     /* Make a closing node, and hook it on the end. */
  367.     ender = regnode((paren) ? CLOSE+parno : END,rcstate);    
  368.     regtail(ret, ender);
  369.  
  370.     /* Hook the tails of the branches to the closing node. */
  371.     for (br = ret; br != NULL; br = regnext(br))
  372.         regoptail(br, ender);
  373.  
  374.     /* Check for proper termination. */
  375.     if (paren && *rcstate->regparse++ != ')') {
  376.         FAIL("unmatched ()");
  377.     } else if (!paren && *rcstate->regparse != '\0') {
  378.         if (*rcstate->regparse == ')') {
  379.             FAIL("unmatched ()");
  380.         } else
  381.             FAIL("junk on end");    /* "Can't happen". */
  382.         /* NOTREACHED */
  383.     }
  384.  
  385.     return(ret);
  386. }
  387.  
  388. /*
  389.  - regbranch - one alternative of an | operator
  390.  *
  391.  * Implements the concatenation operator.
  392.  */
  393. static char *
  394. regbranch(flagp, rcstate)
  395. int *flagp;
  396. struct regcomp_state *rcstate;
  397. {
  398.     register char *ret;
  399.     register char *chain;
  400.     register char *latest;
  401.     int flags;
  402.  
  403.     *flagp = WORST;        /* Tentatively. */
  404.  
  405.     ret = regnode(BRANCH,rcstate);
  406.     chain = NULL;
  407.     while (*rcstate->regparse != '\0' && *rcstate->regparse != '|' &&
  408.                 *rcstate->regparse != ')') {
  409.         latest = regpiece(&flags, rcstate);
  410.         if (latest == NULL)
  411.             return(NULL);
  412.         *flagp |= flags&HASWIDTH;
  413.         if (chain == NULL)    /* First piece. */
  414.             *flagp |= flags&SPSTART;
  415.         else
  416.             regtail(chain, latest);
  417.         chain = latest;
  418.     }
  419.     if (chain == NULL)    /* Loop ran zero times. */
  420.         (void) regnode(NOTHING,rcstate);
  421.  
  422.     return(ret);
  423. }
  424.  
  425. /*
  426.  - regpiece - something followed by possible [*+?]
  427.  *
  428.  * Note that the branching code sequences used for ? and the general cases
  429.  * of * and + are somewhat optimized:  they use the same NOTHING node as
  430.  * both the endmarker for their branch list and the body of the last branch.
  431.  * It might seem that this node could be dispensed with entirely, but the
  432.  * endmarker role is not redundant.
  433.  */
  434. static char *
  435. regpiece(flagp, rcstate)
  436. int *flagp;
  437. struct regcomp_state *rcstate;
  438. {
  439.     register char *ret;
  440.     register char op;
  441.     register char *next;
  442.     int flags;
  443.  
  444.     ret = regatom(&flags,rcstate);
  445.     if (ret == NULL)
  446.         return(NULL);
  447.  
  448.     op = *rcstate->regparse;
  449.     if (!ISMULT(op)) {
  450.         *flagp = flags;
  451.         return(ret);
  452.     }
  453.  
  454.     if (!(flags&HASWIDTH) && op != '?')
  455.         FAIL("*+ operand could be empty");
  456.     *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
  457.  
  458.     if (op == '*' && (flags&SIMPLE))
  459.         reginsert(STAR, ret, rcstate);
  460.     else if (op == '*') {
  461.         /* Emit x* as (x&|), where & means "self". */
  462.         reginsert(BRANCH, ret, rcstate);            /* Either x */
  463.         regoptail(ret, regnode(BACK,rcstate));        /* and loop */
  464.         regoptail(ret, ret);            /* back */
  465.         regtail(ret, regnode(BRANCH,rcstate));        /* or */
  466.         regtail(ret, regnode(NOTHING,rcstate));        /* null. */
  467.     } else if (op == '+' && (flags&SIMPLE))
  468.         reginsert(PLUS, ret, rcstate);
  469.     else if (op == '+') {
  470.         /* Emit x+ as x(&|), where & means "self". */
  471.         next = regnode(BRANCH,rcstate);            /* Either */
  472.         regtail(ret, next);
  473.         regtail(regnode(BACK,rcstate), ret);        /* loop back */
  474.         regtail(next, regnode(BRANCH,rcstate));        /* or */
  475.         regtail(ret, regnode(NOTHING,rcstate));        /* null. */
  476.     } else if (op == '?') {
  477.         /* Emit x? as (x|) */
  478.         reginsert(BRANCH, ret, rcstate);            /* Either x */
  479.         regtail(ret, regnode(BRANCH,rcstate));        /* or */
  480.         next = regnode(NOTHING,rcstate);        /* null. */
  481.         regtail(ret, next);
  482.         regoptail(ret, next);
  483.     }
  484.     rcstate->regparse++;
  485.     if (ISMULT(*rcstate->regparse))
  486.         FAIL("nested *?+");
  487.  
  488.     return(ret);
  489. }
  490.  
  491. /*
  492.  - regatom - the lowest level
  493.  *
  494.  * Optimization:  gobbles an entire sequence of ordinary characters so that
  495.  * it can turn them into a single node, which is smaller to store and
  496.  * faster to run.  Backslashed characters are exceptions, each becoming a
  497.  * separate node; the code is simpler that way and it's not worth fixing.
  498.  */
  499. static char *
  500. regatom(flagp, rcstate)
  501. int *flagp;
  502. struct regcomp_state *rcstate;
  503. {
  504.     register char *ret;
  505.     int flags;
  506.  
  507.     *flagp = WORST;        /* Tentatively. */
  508.  
  509.     switch (*rcstate->regparse++) {
  510.     case '^':
  511.         ret = regnode(BOL,rcstate);
  512.         break;
  513.     case '$':
  514.         ret = regnode(EOL,rcstate);
  515.         break;
  516.     case '.':
  517.         ret = regnode(ANY,rcstate);
  518.         *flagp |= HASWIDTH|SIMPLE;
  519.         break;
  520.     case '[': {
  521.             register int clss;
  522.             register int classend;
  523.  
  524.             if (*rcstate->regparse == '^') {    /* Complement of range. */
  525.                 ret = regnode(ANYBUT,rcstate);
  526.                 rcstate->regparse++;
  527.             } else
  528.                 ret = regnode(ANYOF,rcstate);
  529.             if (*rcstate->regparse == ']' || *rcstate->regparse == '-')
  530.                 regc(*rcstate->regparse++,rcstate);
  531.             while (*rcstate->regparse != '\0' && *rcstate->regparse != ']') {
  532.                 if (*rcstate->regparse == '-') {
  533.                     rcstate->regparse++;
  534.                     if (*rcstate->regparse == ']' || *rcstate->regparse == '\0')
  535.                         regc('-',rcstate);
  536.                     else {
  537.                         clss = UCHARAT(rcstate->regparse-2)+1;
  538.                         classend = UCHARAT(rcstate->regparse);
  539.                         if (clss > classend+1)
  540.                             FAIL("invalid [] range");
  541.                         for (; clss <= classend; clss++)
  542.                             regc(clss,rcstate);
  543.                         rcstate->regparse++;
  544.                     }
  545.                 } else
  546.                     regc(*rcstate->regparse++,rcstate);
  547.             }
  548.             regc('\0',rcstate);
  549.             if (*rcstate->regparse != ']')
  550.                 FAIL("unmatched []");
  551.             rcstate->regparse++;
  552.             *flagp |= HASWIDTH|SIMPLE;
  553.         }
  554.         break;
  555.     case '(':
  556.         ret = reg(1, &flags, rcstate);
  557.         if (ret == NULL)
  558.             return(NULL);
  559.         *flagp |= flags&(HASWIDTH|SPSTART);
  560.         break;
  561.     case '\0':
  562.     case '|':
  563.     case ')':
  564.         FAIL("internal urp");    /* Supposed to be caught earlier. */
  565.         /* NOTREACHED */
  566.         break;
  567.     case '?':
  568.     case '+':
  569.     case '*':
  570.         FAIL("?+* follows nothing");
  571.         /* NOTREACHED */
  572.         break;
  573.     case '\\':
  574.         if (*rcstate->regparse == '\0')
  575.             FAIL("trailing \\");
  576.         ret = regnode(EXACTLY,rcstate);
  577.         regc(*rcstate->regparse++,rcstate);
  578.         regc('\0',rcstate);
  579.         *flagp |= HASWIDTH|SIMPLE;
  580.         break;
  581.     default: {
  582.             register int len;
  583.             register char ender;
  584.  
  585.             rcstate->regparse--;
  586.             len = strcspn(rcstate->regparse, META);
  587.             if (len <= 0)
  588.                 FAIL("internal disaster");
  589.             ender = *(rcstate->regparse+len);
  590.             if (len > 1 && ISMULT(ender))
  591.                 len--;        /* Back off clear of ?+* operand. */
  592.             *flagp |= HASWIDTH;
  593.             if (len == 1)
  594.                 *flagp |= SIMPLE;
  595.             ret = regnode(EXACTLY,rcstate);
  596.             while (len > 0) {
  597.                 regc(*rcstate->regparse++,rcstate);
  598.                 len--;
  599.             }
  600.             regc('\0',rcstate);
  601.         }
  602.         break;
  603.     }
  604.  
  605.     return(ret);
  606. }
  607.  
  608. /*
  609.  - regnode - emit a node
  610.  */
  611. static char *            /* Location. */
  612. regnode(op, rcstate)
  613. char op;
  614. struct regcomp_state *rcstate;
  615. {
  616.     register char *ret;
  617.     register char *ptr;
  618.  
  619.     ret = rcstate->regcode;
  620.     if (ret == ®dummy) {
  621.         rcstate->regsize += 3;
  622.         return(ret);
  623.     }
  624.  
  625.     ptr = ret;
  626.     *ptr++ = op;
  627.     *ptr++ = '\0';        /* Null "next" pointer. */
  628.     *ptr++ = '\0';
  629.     rcstate->regcode = ptr;
  630.  
  631.     return(ret);
  632. }
  633.  
  634. /*
  635.  - regc - emit (if appropriate) a byte of code
  636.  */
  637. static void
  638. regc(b, rcstate)
  639. char b;
  640. struct regcomp_state *rcstate;
  641. {
  642.     if (rcstate->regcode != ®dummy)
  643.         *rcstate->regcode++ = b;
  644.     else
  645.         rcstate->regsize++;
  646. }
  647.  
  648. /*
  649.  - reginsert - insert an operator in front of already-emitted operand
  650.  *
  651.  * Means relocating the operand.
  652.  */
  653. static void
  654. reginsert(op, opnd, rcstate)
  655. char op;
  656. char *opnd;
  657. struct regcomp_state *rcstate;
  658. {
  659.     register char *src;
  660.     register char *dst;
  661.     register char *place;
  662.  
  663.     if (rcstate->regcode == ®dummy) {
  664.         rcstate->regsize += 3;
  665.         return;
  666.     }
  667.  
  668.     src = rcstate->regcode;
  669.     rcstate->regcode += 3;
  670.     dst = rcstate->regcode;
  671.     while (src > opnd)
  672.         *--dst = *--src;
  673.  
  674.     place = opnd;        /* Op node, where operand used to be. */
  675.     *place++ = op;
  676.     *place++ = '\0';
  677.     *place++ = '\0';
  678. }
  679.  
  680. /*
  681.  - regtail - set the next-pointer at the end of a node chain
  682.  */
  683. static void
  684. regtail(p, val)
  685. char *p;
  686. char *val;
  687. {
  688.     register char *scan;
  689.     register char *temp;
  690.     register int offset;
  691.  
  692.     if (p == ®dummy)
  693.         return;
  694.  
  695.     /* Find last node. */
  696.     scan = p;
  697.     for (;;) {
  698.         temp = regnext(scan);
  699.         if (temp == NULL)
  700.             break;
  701.         scan = temp;
  702.     }
  703.  
  704.     if (OP(scan) == BACK)
  705.         offset = scan - val;
  706.     else
  707.         offset = val - scan;
  708.     *(scan+1) = (offset>>8)&0377;
  709.     *(scan+2) = offset&0377;
  710. }
  711.  
  712. /*
  713.  - regoptail - regtail on operand of first argument; nop if operandless
  714.  */
  715. static void
  716. regoptail(p, val)
  717. char *p;
  718. char *val;
  719. {
  720.     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
  721.     if (p == NULL || p == ®dummy || OP(p) != BRANCH)
  722.         return;
  723.     regtail(OPERAND(p), val);
  724. }
  725.  
  726. /*
  727.  * TclRegExec and friends
  728.  */
  729.  
  730. /*
  731.  * Global work variables for TclRegExec().
  732.  */
  733. struct regexec_state  {
  734.     char *reginput;        /* String-input pointer. */
  735.     char *regbol;        /* Beginning of input, for ^ check. */
  736.     char **regstartp;    /* Pointer to startp array. */
  737.     char **regendp;        /* Ditto for endp. */
  738. };
  739.  
  740. /*
  741.  * Forwards.
  742.  */
  743. STATIC int regtry();
  744. STATIC int regmatch();
  745. STATIC int regrepeat();
  746.  
  747. #ifdef DEBUG
  748. int regnarrate = 0;
  749. void regdump();
  750. STATIC char *regprop();
  751. #endif
  752.  
  753. /*
  754.  - TclRegExec - match a regexp against a string
  755.  */
  756. int
  757. TclRegExec(prog, string, start)
  758. register regexp *prog;
  759. register char *string;
  760. char *start;
  761. {
  762.     register char *s;
  763.     struct regexec_state state;
  764.     struct regexec_state *restate= &state;
  765.  
  766.     /* Be paranoid... */
  767.     if (prog == NULL || string == NULL) {
  768.         TclRegError("NULL parameter");
  769.         return(0);
  770.     }
  771.  
  772.     /* Check validity of program. */
  773.     if (UCHARAT(prog->program) != MAGIC) {
  774.         TclRegError("corrupted program");
  775.         return(0);
  776.     }
  777.  
  778.     /* If there is a "must appear" string, look for it. */
  779.     if (prog->regmust != NULL) {
  780.         s = string;
  781.         while ((s = strchr(s, prog->regmust[0])) != NULL) {
  782.             if (strncmp(s, prog->regmust, (size_t) prog->regmlen)
  783.                 == 0)
  784.                 break;    /* Found it. */
  785.             s++;
  786.         }
  787.         if (s == NULL)    /* Not present. */
  788.             return(0);
  789.     }
  790.  
  791.     /* Mark beginning of line for ^ . */
  792.     restate->regbol = start;
  793.  
  794.     /* Simplest case:  anchored match need be tried only once. */
  795.     if (prog->reganch)
  796.         return(regtry(prog, string, restate));
  797.  
  798.     /* Messy cases:  unanchored match. */
  799.     s = string;
  800.     if (prog->regstart != '\0')
  801.         /* We know what char it must start with. */
  802.         while ((s = strchr(s, prog->regstart)) != NULL) {
  803.             if (regtry(prog, s, restate))
  804.                 return(1);
  805.             s++;
  806.         }
  807.     else
  808.         /* We don't -- general case. */
  809.         do {
  810.             if (regtry(prog, s, restate))
  811.                 return(1);
  812.         } while (*s++ != '\0');
  813.  
  814.     /* Failure. */
  815.     return(0);
  816. }
  817.  
  818. /*
  819.  - regtry - try match at specific point
  820.  */
  821. static int            /* 0 failure, 1 success */
  822. regtry(prog, string, restate)
  823. regexp *prog;
  824. char *string;
  825. struct regexec_state *restate;
  826. {
  827.     register int i;
  828.     register char **sp;
  829.     register char **ep;
  830.  
  831.     restate->reginput = string;
  832.     restate->regstartp = prog->startp;
  833.     restate->regendp = prog->endp;
  834.  
  835.     sp = prog->startp;
  836.     ep = prog->endp;
  837.     for (i = NSUBEXP; i > 0; i--) {
  838.         *sp++ = NULL;
  839.         *ep++ = NULL;
  840.     }
  841.     if (regmatch(prog->program + 1,restate)) {
  842.         prog->startp[0] = string;
  843.         prog->endp[0] = restate->reginput;
  844.         return(1);
  845.     } else
  846.         return(0);
  847. }
  848.  
  849. /*
  850.  - regmatch - main matching routine
  851.  *
  852.  * Conceptually the strategy is simple:  check to see whether the current
  853.  * node matches, call self recursively to see whether the rest matches,
  854.  * and then act accordingly.  In practice we make some effort to avoid
  855.  * recursion, in particular by going through "ordinary" nodes (that don't
  856.  * need to know whether the rest of the match failed) by a loop instead of
  857.  * by recursion.
  858.  */
  859. static int            /* 0 failure, 1 success */
  860. regmatch(prog, restate)
  861. char *prog;
  862. struct regexec_state *restate;
  863. {
  864.     register char *scan;    /* Current node. */
  865.     char *next;        /* Next node. */
  866.  
  867.     scan = prog;
  868. #ifdef DEBUG
  869.     if (scan != NULL && regnarrate)
  870.         fprintf(stderr, "%s(\n", regprop(scan));
  871. #endif
  872.     while (scan != NULL) {
  873. #ifdef DEBUG
  874.         if (regnarrate)
  875.             fprintf(stderr, "%s...\n", regprop(scan));
  876. #endif
  877.         next = regnext(scan);
  878.  
  879.         switch (OP(scan)) {
  880.         case BOL:
  881.             if (restate->reginput != restate->regbol)
  882.                 return(0);
  883.             break;
  884.         case EOL:
  885.             if (*restate->reginput != '\0')
  886.                 return(0);
  887.             break;
  888.         case ANY:
  889.             if (*restate->reginput == '\0')
  890.                 return(0);
  891.             restate->reginput++;
  892.             break;
  893.         case EXACTLY: {
  894.                 register int len;
  895.                 register char *opnd;
  896.  
  897.                 opnd = OPERAND(scan);
  898.                 /* Inline the first character, for speed. */
  899.                 if (*opnd != *restate->reginput)
  900.                     return(0);
  901.                 len = strlen(opnd);
  902.                 if (len > 1 && strncmp(opnd, restate->reginput, (size_t) len) != 0)
  903.                     return(0);
  904.                 restate->reginput += len;
  905.             }
  906.             break;
  907.         case ANYOF:
  908.              if (*restate->reginput == '\0' || strchr(OPERAND(scan), *restate->reginput) == NULL)
  909.                 return(0);
  910.             restate->reginput++;
  911.             break;
  912.         case ANYBUT:
  913.              if (*restate->reginput == '\0' || strchr(OPERAND(scan), *restate->reginput) != NULL)
  914.                 return(0);
  915.             restate->reginput++;
  916.             break;
  917.         case NOTHING:
  918.             break;
  919.         case BACK:
  920.             break;
  921.         case OPEN+1:
  922.         case OPEN+2:
  923.         case OPEN+3:
  924.         case OPEN+4:
  925.         case OPEN+5:
  926.         case OPEN+6:
  927.         case OPEN+7:
  928.         case OPEN+8:
  929.         case OPEN+9: {
  930.                 register int no;
  931.                 register char *save;
  932.  
  933.                 no = OP(scan) - OPEN;
  934.                 save = restate->reginput;
  935.  
  936.                 if (regmatch(next,restate)) {
  937.                     /*
  938.                      * Don't set startp if some later
  939.                      * invocation of the same parentheses
  940.                      * already has.
  941.                      */
  942.                     if (restate->regstartp[no] == NULL)
  943.                         restate->regstartp[no] = save;
  944.                     return(1);
  945.                 } else
  946.                     return(0);
  947.             }
  948.             /* NOTREACHED */
  949.             break;
  950.         case CLOSE+1:
  951.         case CLOSE+2:
  952.         case CLOSE+3:
  953.         case CLOSE+4:
  954.         case CLOSE+5:
  955.         case CLOSE+6:
  956.         case CLOSE+7:
  957.         case CLOSE+8:
  958.         case CLOSE+9: {
  959.                 register int no;
  960.                 register char *save;
  961.  
  962.                 no = OP(scan) - CLOSE;
  963.                 save = restate->reginput;
  964.  
  965.                 if (regmatch(next,restate)) {
  966.                     /*
  967.                      * Don't set endp if some later
  968.                      * invocation of the same parentheses
  969.                      * already has.
  970.                      */
  971.                     if (restate->regendp[no] == NULL)
  972.                         restate->regendp[no] = save;
  973.                     return(1);
  974.                 } else
  975.                     return(0);
  976.             }
  977.             /* NOTREACHED */
  978.             break;
  979.         case BRANCH: {
  980.                 register char *save;
  981.  
  982.                 if (OP(next) != BRANCH)        /* No choice. */
  983.                     next = OPERAND(scan);    /* Avoid recursion. */
  984.                 else {
  985.                     do {
  986.                         save = restate->reginput;
  987.                         if (regmatch(OPERAND(scan),restate))
  988.                             return(1);
  989.                         restate->reginput = save;
  990.                         scan = regnext(scan);
  991.                     } while (scan != NULL && OP(scan) == BRANCH);
  992.                     return(0);
  993.                     /* NOTREACHED */
  994.                 }
  995.             }
  996.             /* NOTREACHED */
  997.             break;
  998.         case STAR:
  999.         case PLUS: {
  1000.                 register char nextch;
  1001.                 register int no;
  1002.                 register char *save;
  1003.                 register int min;
  1004.  
  1005.                 /*
  1006.                  * Lookahead to avoid useless match attempts
  1007.                  * when we know what character comes next.
  1008.                  */
  1009.                 nextch = '\0';
  1010.                 if (OP(next) == EXACTLY)
  1011.                     nextch = *OPERAND(next);
  1012.                 min = (OP(scan) == STAR) ? 0 : 1;
  1013.                 save = restate->reginput;
  1014.                 no = regrepeat(OPERAND(scan),restate);
  1015.                 while (no >= min) {
  1016.                     /* If it could work, try it. */
  1017.                     if (nextch == '\0' || *restate->reginput == nextch)
  1018.                         if (regmatch(next,restate))
  1019.                             return(1);
  1020.                     /* Couldn't or didn't -- back up. */
  1021.                     no--;
  1022.                     restate->reginput = save + no;
  1023.                 }
  1024.                 return(0);
  1025.             }
  1026.             /* NOTREACHED */
  1027.             break;
  1028.         case END:
  1029.             return(1);    /* Success! */
  1030.             /* NOTREACHED */
  1031.             break;
  1032.         default:
  1033.             TclRegError("memory corruption");
  1034.             return(0);
  1035.             /* NOTREACHED */
  1036.             break;
  1037.         }
  1038.  
  1039.         scan = next;
  1040.     }
  1041.  
  1042.     /*
  1043.      * We get here only if there's trouble -- normally "case END" is
  1044.      * the terminating point.
  1045.      */
  1046.     TclRegError("corrupted pointers");
  1047.     return(0);
  1048. }
  1049.  
  1050. /*
  1051.  - regrepeat - repeatedly match something simple, report how many
  1052.  */
  1053. static int
  1054. regrepeat(p, restate)
  1055. char *p;
  1056. struct regexec_state *restate;
  1057. {
  1058.     register int count = 0;
  1059.     register char *scan;
  1060.     register char *opnd;
  1061.  
  1062.     scan = restate->reginput;
  1063.     opnd = OPERAND(p);
  1064.     switch (OP(p)) {
  1065.     case ANY:
  1066.         count = strlen(scan);
  1067.         scan += count;
  1068.         break;
  1069.     case EXACTLY:
  1070.         while (*opnd == *scan) {
  1071.             count++;
  1072.             scan++;
  1073.         }
  1074.         break;
  1075.     case ANYOF:
  1076.         while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
  1077.             count++;
  1078.             scan++;
  1079.         }
  1080.         break;
  1081.     case ANYBUT:
  1082.         while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
  1083.             count++;
  1084.             scan++;
  1085.         }
  1086.         break;
  1087.     default:        /* Oh dear.  Called inappropriately. */
  1088.         TclRegError("internal foulup");
  1089.         count = 0;    /* Best compromise. */
  1090.         break;
  1091.     }
  1092.     restate->reginput = scan;
  1093.  
  1094.     return(count);
  1095. }
  1096.  
  1097. /*
  1098.  - regnext - dig the "next" pointer out of a node
  1099.  */
  1100. static char *
  1101. regnext(p)
  1102. register char *p;
  1103. {
  1104.     register int offset;
  1105.  
  1106.     if (p == ®dummy)
  1107.         return(NULL);
  1108.  
  1109.     offset = NEXT(p);
  1110.     if (offset == 0)
  1111.         return(NULL);
  1112.  
  1113.     if (OP(p) == BACK)
  1114.         return(p-offset);
  1115.     else
  1116.         return(p+offset);
  1117. }
  1118.  
  1119. #ifdef DEBUG
  1120.  
  1121. STATIC char *regprop();
  1122.  
  1123. /*
  1124.  - regdump - dump a regexp onto stdout in vaguely comprehensible form
  1125.  */
  1126. void
  1127. regdump(r)
  1128. regexp *r;
  1129. {
  1130.     register char *s;
  1131.     register char op = EXACTLY;    /* Arbitrary non-END op. */
  1132.     register char *next;
  1133.  
  1134.  
  1135.     s = r->program + 1;
  1136.     while (op != END) {    /* While that wasn't END last time... */
  1137.         op = OP(s);
  1138.         printf("%2d%s", s-r->program, regprop(s));    /* Where, what. */
  1139.         next = regnext(s);
  1140.         if (next == NULL)        /* Next ptr. */
  1141.             printf("(0)");
  1142.         else 
  1143.             printf("(%d)", (s-r->program)+(next-s));
  1144.         s += 3;
  1145.         if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
  1146.             /* Literal string, where present. */
  1147.             while (*s != '\0') {
  1148.                 putchar(*s);
  1149.                 s++;
  1150.             }
  1151.             s++;
  1152.         }
  1153.         putchar('\n');
  1154.     }
  1155.  
  1156.     /* Header fields of interest. */
  1157.     if (r->regstart != '\0')
  1158.         printf("start `%c' ", r->regstart);
  1159.     if (r->reganch)
  1160.         printf("anchored ");
  1161.     if (r->regmust != NULL)
  1162.         printf("must have \"%s\"", r->regmust);
  1163.     printf("\n");
  1164. }
  1165.  
  1166. /*
  1167.  - regprop - printable representation of opcode
  1168.  */
  1169. static char *
  1170. regprop(op)
  1171. char *op;
  1172. {
  1173.     register char *p;
  1174.     static char buf[50];
  1175.  
  1176.     (void) strcpy(buf, ":");
  1177.  
  1178.     switch (OP(op)) {
  1179.     case BOL:
  1180.         p = "BOL";
  1181.         break;
  1182.     case EOL:
  1183.         p = "EOL";
  1184.         break;
  1185.     case ANY:
  1186.         p = "ANY";
  1187.         break;
  1188.     case ANYOF:
  1189.         p = "ANYOF";
  1190.         break;
  1191.     case ANYBUT:
  1192.         p = "ANYBUT";
  1193.         break;
  1194.     case BRANCH:
  1195.         p = "BRANCH";
  1196.         break;
  1197.     case EXACTLY:
  1198.         p = "EXACTLY";
  1199.         break;
  1200.     case NOTHING:
  1201.         p = "NOTHING";
  1202.         break;
  1203.     case BACK:
  1204.         p = "BACK";
  1205.         break;
  1206.     case END:
  1207.         p = "END";
  1208.         break;
  1209.     case OPEN+1:
  1210.     case OPEN+2:
  1211.     case OPEN+3:
  1212.     case OPEN+4:
  1213.     case OPEN+5:
  1214.     case OPEN+6:
  1215.     case OPEN+7:
  1216.     case OPEN+8:
  1217.     case OPEN+9:
  1218.         sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
  1219.         p = NULL;
  1220.         break;
  1221.     case CLOSE+1:
  1222.     case CLOSE+2:
  1223.     case CLOSE+3:
  1224.     case CLOSE+4:
  1225.     case CLOSE+5:
  1226.     case CLOSE+6:
  1227.     case CLOSE+7:
  1228.     case CLOSE+8:
  1229.     case CLOSE+9:
  1230.         sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
  1231.         p = NULL;
  1232.         break;
  1233.     case STAR:
  1234.         p = "STAR";
  1235.         break;
  1236.     case PLUS:
  1237.         p = "PLUS";
  1238.         break;
  1239.     default:
  1240.         TclRegError("corrupted opcode");
  1241.         break;
  1242.     }
  1243.     if (p != NULL)
  1244.         (void) strcat(buf, p);
  1245.     return(buf);
  1246. }
  1247. #endif
  1248.  
  1249. /*
  1250.  * The following is provided for those people who do not have strcspn() in
  1251.  * their C libraries.  They should get off their butts and do something
  1252.  * about it; at least one public-domain implementation of those (highly
  1253.  * useful) string routines has been published on Usenet.
  1254.  */
  1255. #ifdef STRCSPN
  1256. /*
  1257.  * strcspn - find length of initial segment of s1 consisting entirely
  1258.  * of characters not from s2
  1259.  */
  1260.  
  1261. static int
  1262. strcspn(s1, s2)
  1263. char *s1;
  1264. char *s2;
  1265. {
  1266.     register char *scan1;
  1267.     register char *scan2;
  1268.     register int count;
  1269.  
  1270.     count = 0;
  1271.     for (scan1 = s1; *scan1 != '\0'; scan1++) {
  1272.         for (scan2 = s2; *scan2 != '\0';)    /* ++ moved down. */
  1273.             if (*scan1 == *scan2++)
  1274.                 return(count);
  1275.         count++;
  1276.     }
  1277.     return(count);
  1278. }
  1279. #endif
  1280.  
  1281. /*
  1282.  *----------------------------------------------------------------------
  1283.  *
  1284.  * TclRegError --
  1285.  *
  1286.  *    This procedure is invoked by the regexp code when an error
  1287.  *    occurs.  It saves the error message so it can be seen by the
  1288.  *    code that called Spencer's code.
  1289.  *
  1290.  * Results:
  1291.  *    None.
  1292.  *
  1293.  * Side effects:
  1294.  *    The value of "string" is saved in "errMsg".
  1295.  *
  1296.  *----------------------------------------------------------------------
  1297.  */
  1298.  
  1299. void
  1300. TclRegError(string)
  1301.     char *string;            /* Error message. */
  1302. {
  1303.     errMsg = string;
  1304. }
  1305.  
  1306. char *
  1307. TclGetRegError()
  1308. {
  1309.     return errMsg;
  1310. }
  1311.